#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os

## Factory tools
# 

## Module tools class
class ModuleTools(object):
    ## add folder to path
    # @param folder_path path of the folder
    @staticmethod
    def add_module_folder(folder_path):
        path_to_import = sys.argv[0]
        path_to_import = os.path.dirname(path_to_import)
        path_to_import = path_to_import + '/' + folder_path
        sys.path.append(path_to_import)
    
    ## reload a module
    # @param module_name name of the module to reload
    @staticmethod
    def reload_module(module_name):
        modul = __import__(str(module_name))
        modul = reload(modul)

## Generic factory
class ClassFactory(object):
    ## get class from a module by class name
    # @param module_name name of the module containing class
    # @param class_name name of the class to load  
    @staticmethod
    def get_class(module_name, class_name):        
        modul = __import__(str(module_name))
        modul = reload(modul)
        clazz = modul.__dict__[class_name]
        return clazz
    
    @staticmethod
    def get_object_by_name(module_name, object_name, refresh=True):
        modul = __import__(str(module_name))
        if refresh:
            modul = reload(modul)
        obj = modul.__dict__[object_name]
        return obj
    
    @staticmethod
    def get_object_by_type(module_name, klass, refresh=True):
        result = []
        try:
            modul = __import__(str(module_name))
            if refresh:
                modul = reload(modul)
            for cl in dir(modul):
                obj = ClassFactory.get_object_by_name(module_name, cl, refresh=False)
                if type(obj) is type:
                    if issubclass(obj, klass):
                        result.append(obj)
        except StandardError, e:
            print str(e)
                    
        return result
        